package com.changan.generator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;
import com.baomidou.mybatisplus.generator.query.SQLQuery;
import org.apache.ibatis.type.JdbcType;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CodeGenerator {

    public static void main(String[] args) {
        // 项目根路径
        String projectPath = System.getProperty("user.dir");

        FastAutoGenerator.create("jdbc:mysql://localhost:3306/zbxyxt?characterEncoding=UTF-8&useUnicode=true&serverTimezone=GMT%2B8", "root", "root")
                // 数据源配置
                .dataSourceConfig(builder ->
                        builder.databaseQueryClass(SQLQuery.class)
                                .typeConvert(new MySqlTypeConvert())
                                .typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                                    // 兼容旧版本转换成Integer
                                    if (JdbcType.TINYINT == metaInfo.getJdbcType()) {
                                        return DbColumnType.INTEGER;
                                    }
                                    return typeRegistry.getColumnType(metaInfo);
                                })
                                .dbQuery(new MySqlQuery())
                )
                // 全局配置
                .globalConfig(builder -> builder
                        .author("NieChangan")
                        .outputDir(projectPath + "/src/main/java")  // Java代码输出目录
                        .commentDate("yyyy-MM-dd")
                )
                // 包配置
                .packageConfig(builder -> builder
                        .parent("com.changan")
                        .entity("entity")
                        .mapper("mapper")
                        .controller("controller")
                        .service("service")
                        .serviceImpl("service.impl")
                        .xml("mapper")  // XML文件的包名
                        // 指定各模块的输出路径
                        .pathInfo(Collections.singletonMap(
                                OutputFile.xml,
                                projectPath + "/src/main/resources/mapper/"  // XML文件输出到resources目录
                        ))
                )
                // 策略配置
                .strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("请输入表名，多个英文逗号分隔？所有输入 all")))
                        .addTablePrefix("t_", "c_") // 设置过滤表前缀
                        .entityBuilder()
                        .disableSerialVersionUID()
                        .enableChainModel()
                        .enableLombok()
                        .enableRemoveIsPrefix()
                        .enableTableFieldAnnotation()
                        .enableActiveRecord()
                        .versionColumnName("version")
                        .versionPropertyName("version")
                        .logicDeleteColumnName("deleted")
                        .logicDeletePropertyName("deleted")
                        //驼峰命名
                        .naming(NamingStrategy.underline_to_camel)
                        .columnNaming(NamingStrategy.underline_to_camel)
                        //.addSuperEntityColumns("id", "created_by", "created_time", "updated_by", "updated_time")
                        //.addIgnoreColumns("age")
                        .addTableFills(new Column("create_time", FieldFill.INSERT))
                        .addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE))
                        //根据主键自动生成ID
                        .idType(IdType.AUTO)
                        .formatFileName("%s")
                        .controllerBuilder()
                        .enableRestStyle()
                        .formatFileName("%sController")
                        .serviceBuilder()
                        .formatServiceFileName("%sService")
                        .formatServiceImplFileName("%sServiceImpl")
                        .mapperBuilder()
                        .superClass(BaseMapper.class)
                        .enableBaseResultMap()
                        .enableBaseColumnList()
                        //.cache(MyMapperCache.class)
                        .formatMapperFileName("%sMapper")
                        .formatXmlFileName("%sMapper")
                        .build())

                // 使用Freemarker引擎模板
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }

    // 处理 all 情况
    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }
}

